"""
redis 工具类
"""
import json
from typing import Union
from App.exts import redis_client
from objtyping import to_primitive


class RedisUtils:
    @staticmethod
    def get_redis_client():
        return redis_client

    @staticmethod
    def set(key: str, value: any, expire_seconds=None) -> bool:
        str_value = ''
        if value is None:
            return False
        elif isinstance(value, str):
            str_value = value
        elif isinstance(value, dict):
            str_value = json.dumps(value)
        else:
            str_value = json.dumps(to_primitive(value))
        return redis_client.set(key, str_value, expire_seconds)

    @staticmethod
    def get(key: str, value_type=str) -> Union[dict, str]:
        str_value = redis_client.get(key)
        if value_type == str:
            return str_value
        else:
            return json.loads(str_value)
